/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities.User;
import factory.DBConnectionFactory;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author theworldiwant
 */
public class MySQLUserDAO extends UserDAO{
   
    public MySQLUserDAO(){
           try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
  
            PreparedStatement pstmt3 = conn.prepareStatement("SELECT * FROM usertypereference");
            ResultSet rs = pstmt3.executeQuery();
            int n=0;
            while(rs.next())
                n++;
            //init
            if(n==0){
                PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `webdeve`.`usertypereference` (`id`, `name`, `description`) VALUES ('1', 'admin', 'for admin')");
                PreparedStatement pstmt2 = conn.prepareStatement("INSERT INTO `webdeve`.`usertypereference` (`id`, `name`, `description`) VALUES ('2', 'common user', 'for common user')");
               
                pstmt.executeUpdate();
                pstmt2.executeUpdate();
                 User user=new User();
        
                user.setId(1);
                user.setActOrPass("active");
                user.setPassword("admin");
                user.setUsername("admin");
                user.setUserTypeId(1);
                user.setGender('F');
                addUser(user);
            }
            conn.close();
        } catch (SQLException ex) {
           
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }  
    private int getCurId(){
            int ctr=0;
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt2;
        try {
            pstmt2 = conn.prepareStatement("select id from users");
            ResultSet rs=pstmt2.executeQuery();
            while(rs.next())
                ctr=rs.getInt("id");
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
           
            
        return ctr;
    }
    @Override
    public void addUser(User obj) {
         try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            
            PreparedStatement pstmt = conn.prepareStatement("insert into users(id,username,password,userTypeId, active, profilePic, age, gender, location, bday, shippingAddress) values (?,?,?,?,?,?,?,?,?,?,?) ");
         
            pstmt.setInt(1, getCurId()+1);
            pstmt.setString(2, obj.getUsername());
            pstmt.setString(3, this.encodePass(obj.getPassword()));
            pstmt.setInt(4, obj.getUserTypeId());
            pstmt.setString(5, obj.getActOrPass());
            pstmt.setString(6, obj.getProfilePic());
            pstmt.setInt(7, obj.getAge());
            pstmt.setString(8, obj.getGender()+"");
            pstmt.setString(9, obj.getLocation());
            pstmt.setDate(10, obj.getBday());
            pstmt.setString(11, obj.getShoppingAddress());
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void updateUser(User obj) {

       try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("UPDATE `webdeve`.`users` SET `username`=?, `password`=?, `userTypeId`=?, `active`=?, `profilePic`=?, `age`=?, `gender`=?, `location`=?, `bday`=?, `shippingAddress`=? WHERE `id`="+obj.getId());
            pstmt.setString(1, obj.getUsername());
            pstmt.setString(2, this.encodePass(obj.getPassword()));
            pstmt.setInt(3, obj.getUserTypeId());
            pstmt.setString(4, obj.getActOrPass());
            pstmt.setString(5, obj.getProfilePic());
            pstmt.setInt(6, obj.getAge());
            pstmt.setString(7, obj.getGender()+"");
            pstmt.setString(8, obj.getLocation());
            pstmt.setDate(9, obj.getBday());
            pstmt.setString(10, obj.getShoppingAddress());
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void activateUser(User obj) {
            
       try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("UPDATE `webdeve`.`users` SET  `active`='active' WHERE `id`="+obj.getId());
            
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    
    

    @Override
    public void deActivateUser(User obj) {
         try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("UPDATE `webdeve`.`users` SET  `active`='passive' WHERE `id`="+obj.getId());
            
            pstmt.executeUpdate();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public User findUserByName(String s) {
       User user= new User();
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users where username=?");
            pstmt.setString(1, s);
            ResultSet rs= pstmt.executeQuery();
          
            while(rs.next()){
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setUserTypeId(rs.getInt("userTypeId"));
                user.setActOrPass(rs.getString("active"));
                user.setProfilePic(rs.getString("profilePic"));
                
                user.setGender(rs.getString("gender").charAt(0));
                user.setLocation(rs.getString("location"));
                user.setBday(rs.getDate("bday"));
                user.setShoppingAddress(rs.getString("shippingAddress"));
                
            }
            conn.close();
             return user;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public User findUserById(String k) {
         User user= new User();
          try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users where id=?");
            pstmt.setString(1, k);
            ResultSet rs= pstmt.executeQuery();
              while(rs.next()){
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setUserTypeId(rs.getInt("userTypeId"));
                user.setActOrPass(rs.getString("active"));
                user.setProfilePic(rs.getString("profilePic"));
           
                user.setGender(rs.getString("gender").charAt(0));
                user.setLocation(rs.getString("location"));
                user.setBday(rs.getDate("bday"));
                user.setShoppingAddress(rs.getString("shippingAddress"));
                
            }
            conn.close();
             return user;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public User validateUser(String username, String password) {
         User user;
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users where username='"+username+"';");
            ResultSet rs= pstmt.executeQuery();
          user= new User();
            while(rs.next()){
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setUserTypeId(rs.getInt("userTypeId"));
                user.setActOrPass(rs.getString("active"));
                user.setProfilePic(rs.getString("profilePic"));
               
                user.setGender(rs.getString("gender").charAt(0));
                user.setLocation(rs.getString("location"));
                user.setBday(rs.getDate("bday"));
                user.setShoppingAddress(rs.getString("shippingAddress"));
            }
            
            conn.close();
            //if(user!=null&&this.isPasswordMatch(encodePass(password), user.getPassword()))
                 return user;
            
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
           
             return null;
        
    } 
    @Override
    public String encodePass(String pass){
       return pass;
    }

    @Override
    public boolean isPasswordMatch(String password, String pass2) {
         if(encodePass(password).equals(encodePass(pass2)))
            return true;
        
        else
            return false;
    }
    
    
}
